package cn.nlsde.controller;


import cn.nlsde.entity.Company;
import cn.nlsde.entity.Template;
import cn.nlsde.service.CompanyService;
import cn.nlsde.service.ExcelService;
import cn.nlsde.service.TemplateService;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by by on 2016/10/24.
 */

@Controller
@RequestMapping("evaluation")
public class EvaluationController {

    @Autowired
    ExcelService excelService;
    @Autowired
    TemplateService templateService;
    @Autowired
    CompanyService companyService;
    private static final Logger logger = LoggerFactory.getLogger(TemplateController.class);

    @RequestMapping("/useTemplate")
    public ModelAndView useTemplate(Integer templateId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("evaluateUse");
        modelAndView.addObject("templateId", templateId);
        Template template = templateService.selectById(templateId);
        modelAndView.addObject("template",template.getTemplateName());

        return modelAndView;
    }

    /**
     * 上传
     */
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("templateId") Integer templateId,
                         @RequestParam("file") MultipartFile file) {
        String name = file.getName();
        Pair<Boolean, String> xlsx = ImmutablePair.of(true, null);
        try {
            xlsx = excelService.getEvaluation(templateId, file.getBytes(), file.getName().endsWith("xlsx"));
        } catch (IOException e) {
            xlsx = ImmutablePair.of(false,e.getMessage());
            return "error";
        }
        return "ok";
    }

    /**
     * 下载
     */
    @RequestMapping(value = "download")
    public void upload(@RequestParam("templateId") Integer templateId,
                       HttpServletResponse response) {
        String templateName = templateService.getTemplateNameById(templateId);
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(templateName,"UTF-8")+".xls");
        } catch (UnsupportedEncodingException e) {
           logger.info("{}",e.getMessage());
        }
        byte[] templateById = templateService.getTemplateById(templateId);
        if (templateById.length > 0) {
            try {
                response.getOutputStream().write(templateById);
            } catch (IOException e) {
                logger.info("{}",e.getMessage());
            }
        }
    }

    /**
     * 排序展示排名靠前的n家
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "displayAnalysisResult")
    public String displayAnalysisResult(@RequestParam("templateId") Integer templateId, ModelMap modelMap) {
        Integer offset = 0;
        Integer limit = 20;
        //综合能力
        List<Company> listComAbility = companyService.selectOrdered(offset, limit, templateId);
        List<Pair<String, Double>> comAbility = new ArrayList<>(listComAbility.size());
        for (Company company : listComAbility) {
            comAbility.add(ImmutablePair.of(company.getCompanyName(), (company.getInnovationFoundationCondition()
                    + company.getInnovationOutputCapacity()
                    + company.getInnovationPracticalCapacity()
                    + company.getInnovativeInputCapacity()
                    + company.getOtherCapacity()) * 100));
        }

        //创新输入
        Map innovateInputMap = new HashMap<>();
        innovateInputMap.put("templateId", templateId);
        innovateInputMap.put("condition", "Innovative_input_capacity");
        innovateInputMap.put("offset", offset);
        innovateInputMap.put("limit", limit);
        List<Company> listInnovateInput = companyService.selectByCondition(innovateInputMap);
        List<Pair<String, Double>> innovateInput = new ArrayList<>(listInnovateInput.size());
        for (Company company : listInnovateInput) {
            innovateInput.add(ImmutablePair.of(company.getCompanyName(), company.getInnovativeInputCapacity() * 100));
        }

        //创新产出
        Map innovateOutMap = new HashMap<>();
        innovateOutMap.put("templateId", templateId);
        innovateOutMap.put("condition", "innovation_output_capacity");
        innovateOutMap.put("offset", offset);
        innovateOutMap.put("limit", limit);
        List<Company> listInnovateOut = companyService.selectByCondition(innovateOutMap);
        List<Pair<String, Double>> innovateOut = new ArrayList<>(listInnovateOut.size());
        for (Company company : listInnovateOut) {
            innovateOut.add(ImmutablePair.of(company.getCompanyName(), company.getInnovationOutputCapacity() * 100));
        }

        //创新实现能力
        Map innovatePracticalMap = new HashMap<>();
        innovatePracticalMap.put("templateId", templateId);
        innovatePracticalMap.put("condition", "Innovation_practical_capacity");
        innovatePracticalMap.put("offset", offset);
        innovatePracticalMap.put("limit", limit);
        List<Company> listInnovatePractical = companyService.selectByCondition(innovatePracticalMap);
        List<Pair<String, Double>> innovatePractical = new ArrayList<>(listInnovatePractical.size());
        for (Company company : listInnovatePractical) {
            innovatePractical.add(ImmutablePair.of(company.getCompanyName(), company.getInnovationPracticalCapacity() * 100));
        }

        //创新基础
        Map innovateFoundationMap = new HashMap<>();
        innovateFoundationMap.put("templateId", templateId);
        innovateFoundationMap.put("condition", "Innovation_foundation_condition");
        innovateFoundationMap.put("offset", offset);
        innovateFoundationMap.put("limit", limit);
        List<Company> listInnovateFoundation = companyService.selectByCondition(innovateFoundationMap);
        List<Pair<String, Double>> innovateFoundation = new ArrayList<>(listInnovateFoundation.size());
        for (Company company : listInnovateFoundation) {
            innovateFoundation.add(ImmutablePair.of(company.getCompanyName(), company.getInnovationFoundationCondition() * 100));
        }
        modelMap.addAttribute("comAbility", comAbility);
        modelMap.addAttribute("innovateInput", innovateInput);
        modelMap.addAttribute("innovateOut", innovateOut);
        modelMap.addAttribute("innovatePractical", innovatePractical);
        modelMap.addAttribute("innovateFoundation", innovateFoundation);
        modelMap.addAttribute("templateId", templateId);
        return "evaluateResult";
    }
    /**
     * 下载
     */
    @RequestMapping(value = "dowloadConpany")
    public void dowloadConpany(@RequestParam("templateId") Integer templateId,
                               HttpServletResponse response) {
        String templateName = templateService.getTemplateNameById(templateId);
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(templateName+"评测结果", "UTF-8") + ".xls");
        } catch (UnsupportedEncodingException e) {
            logger.info("{}", e.getMessage());
        }
        byte[] templateById = companyService.getCompanyBytemplateId(templateId);
        if (templateById.length > 0) {
            try {
                response.getOutputStream().write(templateById);
            } catch (IOException e) {
                logger.info("{}", e.getMessage());
            }
        }
    }
}
